<template>
    <div>
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>用户管理</el-breadcrumb-item>
            <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>
        <el-card>
            <el-row :gutter="30">
                <el-col :span="8">
                    <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserList">
                        <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
                    </el-input>
                </el-col>
                <el-col :span="4">
                    <el-button type="primary" @click="showAddDialog('addFormRef')">添加用户</el-button>
                </el-col>
            </el-row>
            <el-table
                    :data="userList"
                    border
                    stripe
                    style="width: 100%"
                    :header-cell-style="{textAlign: 'center'}"
                    :cell-style="{ textAlign: 'center' }"
            >
                <el-table-column
                        type="index"
                        label="#"
                >
                </el-table-column>
                <el-table-column
                        prop="username"
                        label="姓名"
                        width="180">
                </el-table-column>
                <el-table-column
                        prop="email"
                        label="邮箱"
                        width="250">
                </el-table-column>
                <el-table-column
                        width="150"
                        prop="mobile"
                        label="电话">
                </el-table-column>
                <el-table-column
                        width="180"
                        prop="role_name"
                        label="角色">
                </el-table-column>
                <el-table-column
                        label="状态"
                        width="150"
                >
                    <template slot-scope="scope">
                        <el-switch
                                v-model="scope.row.mg_state"
                                active-color="#13ce66"
                                @change='changeStatus(scope.row)'
                        >
                        </el-switch>
                    </template>
                </el-table-column>
                <el-table-column
                        label="操作">
                    <template slot-scope="scope">
                        <el-tooltip content="编辑" :enterable="false" placement="top-start">
                            <el-button
                                    size="medium"
                                    type="primary"
                                    class="el-icon-edit"
                                    @click="showEditDialog(scope.row.id)"
                            ></el-button>
                        </el-tooltip>
                        <el-tooltip content="删除" :enterable="false" placement="top-start">
                            <el-button
                                    size="medium"
                                    type="danger"
                                    class="el-icon-delete"
                                    @click="removeUserById(scope.row.id)"
                            ></el-button>
                        </el-tooltip>
                        <el-tooltip content="分配角色" :enterable="false" placement="top-start">
                            <el-button
                                    size="medium"
                                    type="warning"
                                    class="el-icon-setting"
                                    @click="showRoleDialog(scope.row)"
                            ></el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination
                    background
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="queryInfo.pageNum"
                    :page-sizes="[1, 3, 5, 7]"
                    :page-size="queryInfo.pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
            </el-pagination>
        </el-card>
        <el-dialog
                title="添加用户"
                :visible.sync="addDialogVisible"
                width="50%"
        >
            <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="addForm.username"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model="addForm.password"></el-input>
                </el-form-item>
                <el-form-item label="手机" prop="mobile">
                    <el-input v-model="addForm.mobile"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="addForm.email"></el-input>
                </el-form-item>

            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="add('addFormRef')">确 定</el-button>
            </span>
        </el-dialog>
        <el-dialog
                title="编辑用户"
                :visible.sync="editDialogVisible"
                width="50%"
        >
            <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="editForm.username" disabled></el-input>
                </el-form-item>
                <el-form-item label="手机" prop="mobile">
                    <el-input v-model="editForm.mobile"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="editForm.email"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="edit('editFormRef')">确 定</el-button>
            </span>
        </el-dialog>
        <el-dialog
                title="分配角色"
                :visible.sync="roleDialogVisible"
                width="50%"
                @close="closeRoleDialog()"
        >
            <div style="font-size: 25px">
                <p>
                    当前用户：{{userInfo.username}}
                </p>
                <br>
                <p>当前角色：{{userInfo.role_name}}</p>
                <br>
                <p>
                    分配新角色：
                    <el-select v-model="selectedRoleId" placeholder="请选择">
                        <el-option
                                v-for="item in roleList"
                                :key="item.id"
                                :label="item.roleName"
                                :value="item.id">
                        </el-option>
                    </el-select>
                </p>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="roleDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="updateRole()">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
  export default {
    name: "Users",
    data() {
      let checkEmail = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('邮箱不能为空'));
        }
        let emailReg = /^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/;
        if (!emailReg.test(value)) {
          callback('邮箱不合法');
        } else {
          callback();
        }
      };
      let checkMobile = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('手机号不能为空'));
        }
        let mobileReg = /^1[0-9]{10}$/;
        if (!mobileReg.test(value)) {
          callback('手机号不合法');
        } else {
          callback();
        }
      };
      return {
        queryInfo: {
          query: '',
          pageNum: 1,
          pageSize: 5
        },
        userList: [],
        userInfo: {},
        total: 0,
        addDialogVisible: false,
        addForm: {
          username: '',
          password: '',
          mobile: '',
          email: ''
        },
        addFormRules: {
          username: [
            {required: true, message: '请输入用户名', trigger: 'blur'},
            {min: 5, max: 10, message: `长度在 5 到 10 个字符`, trigger: 'blur'}
          ],
          password: [
            {required: true, message: '请输入密码', trigger: 'blur'},
            {min: 5, max: 10, message: `长度在 5 到 10 个字符`, trigger: 'blur'}
          ],
          mobile: [
            {required: true, message: '请输入手机号', trigger: 'blur'},
            {validator: checkMobile, trigger: 'blur'},
          ],
          email: [
            {required: true, message: '请输入邮箱', trigger: 'blur'},
            {validator: checkEmail, trigger: 'blur'},
          ],
        },
        editForm: {},
        editFormRules: {
          mobile: [
            {required: true, message: '请输入手机号', trigger: 'blur'},
            {validator: checkMobile, trigger: 'blur'},
          ],
          email: [
            {required: true, message: '请输入邮箱', trigger: 'blur'},
            {validator: checkEmail, trigger: 'blur'},
          ]
        },
        editDialogVisible: false,
        roleDialogVisible: false,
        roleList: [],
        selectedRoleId: ''
      }
    },
    created() {
      this.getUserList();
    },
    methods: {
      async getUserList() {
        const {data: res} = await this.$http({
          url: 'users',
          method: 'get',
          params: this.queryInfo
        });
        if (res.meta.status === 403) return this.$message.error(res.meta.msg);
        if (res.meta.status !== 200) return this.$message.error('获取用户列表失败');
        this.total = res.data.total;
        this.userList = res.data.users;
      },
      handleSizeChange(newSize) {
        this.queryInfo.pageSize = newSize;
        this.getUserList();
      },
      handleCurrentChange(newPage) {
        this.queryInfo.pageNum = newPage;
        this.getUserList();
      },
      showAddDialog(formName) {
        if (this.$refs[formName] !== undefined) {
          this.$refs[formName].resetFields();
        }
        this.addDialogVisible = true;
      },
      async showRoleDialog(userInfo) {
        this.userInfo = userInfo;
        const {data: res} = await this.$http({
          url: 'roles',
          method: 'get'
        });
        if (res.meta.status === 403) return this.$message.error(res.meta.msg);
        if (res.meta.status !== 200) return this.$message.error('获取角色列表失败');
        let list = res.data;
        let index = list.findIndex((item) => {
          return item.roleName === this.userInfo.role_name;
        });
        //删除元素后，返回删除元素的集合，不是剩余元素的集合，改变原数组
        list.splice(index,1);
        this.roleList = list;
        this.roleDialogVisible = true;
      },
      add(formName) {
        this.$refs[formName].validate(async (valid) => {
          if (valid) {
            const {data: res} = await this.$http({
              url: 'users',
              method: 'post',
              data: this.addForm
            });
            if (res.meta.status === 403) return this.$message.error(res.meta.msg);
            if (res.meta.status !== 201) return this.$message.error('添加用户失败');
            this.addDialogVisible = false;
            this.getUserList();
            return this.$message.success('添加用户成功');
          }
        });
      },
      async showEditDialog(id) {
        const {data: res} = await this.$http({
          url: 'users/' + id,
          method: 'get',
        });
        if (res.meta.status === 403) return this.$message.error(res.meta.msg);
        if (res.meta.status !== 200) return this.$message.success('获取用户信息失败');
        this.editForm = res.data;
        this.editDialogVisible = true;
      },
      edit(formName) {
        this.$refs[formName].validate(async (valid) => {
          if (valid) {
            this.editDialogVisible = false;
            const {data: res} = await this.$http({
              url: 'users/' + this.editForm.id,
              method: 'put',
              data: this.editForm
            });
            if (res.meta.status === 403) return this.$message.error(res.meta.msg);
            if (res.meta.status !== 200) return this.$message.error('修改用户信息失败');
            this.getUserList();
            return this.$message.success('修改用户信息成功');
          }
        });
      },
      async removeUserById(id) {
        const confirmResult = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err);
        if (confirmResult === 'confirm') {
          const {data: res} = await this.$http({
            url: 'users/' + id,
            method: 'delete',
          });
          if (res.meta.status === 403) return this.$message.error(res.meta.msg);
          if (res.meta.status !== 200) return this.$message.error('删除用户失败');
          this.getUserList();
          this.$message.success('删除用户成功');
        } else {
          this.$message.info('已取消删除');
        }
      },
      closeRoleDialog() {
        this.selectedRoleId = '';
      },
      async updateRole() {
        if (this.selectedRoleId === '') {
          return this.$message.error('请分配新角色');
        }
        const {data: res} = await this.$http({
          url: `users/${this.userInfo.id}/role`,
          method: 'put',
          data: {rid: this.selectedRoleId}
        });
        if (res.meta.status === 403) return this.$message.error(res.meta.msg);
        if (res.meta.status !== 200) return this.$message.error('分配角色失败');
        this.$message.success('分配角色成功');
        this.userList = this.getUserList();
        this.roleDialogVisible = false;
      },
      async changeStatus(row){
        if (row.id === 500){
          row.mg_state = !row.mg_state;
          return this.$message.error('您没有权限进行该操作，请联系开发人员');
        }
        const {data: res} = await this.$http({
          url: `users/${row.id}/state/${row.mg_state}`,
          method: 'put'
        });
        if (res.meta.status === 403) return this.$message.error(res.meta.msg);
        if (res.meta.status !== 200) return this.$message.error('设置状态失败');
        this.$message.success('设置状态成功');

      },

    }
  }
</script>

<style scoped>
    .el-breadcrumb {
        margin-bottom: 20px;
    }

    .el-table {
        margin-top: 20px;
        margin-bottom: 30px;
    }
</style>
